package presentation;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import db.DbUtils;
import db.Picture;


 public class DeleteAlbumServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

		private static final long serialVersionUID = 1L;
		
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Session hbSession = DbUtils.startSession();
		request.setCharacterEncoding("UTF-8");
		Long albumId = Long.parseLong(request.getParameter("album_id"));
		try {
			String path = this.getServletContext().getInitParameter("IMAGES_DIRECTORY");
			path = this.getServletContext().getRealPath(path);
			File deletedDir = new File(path + File.separatorChar + "deleted");
    		deletedDir.mkdir();
			for (Picture picture : DbUtils.getAlbumbyId(hbSession, albumId).getPictures()) {
				Long imageId = picture.getPictureId();
				String format = picture.getPictureFormat();
	    		File pictureFile = new File(path + File.separatorChar + imageId + "." + format);
	    		pictureFile.renameTo(new File(deletedDir.getAbsolutePath() + File.separatorChar + imageId + "." + format));
	    		pictureFile = new File(path + File.separatorChar + "m_" +  imageId + "." + format);
	    		pictureFile.delete();
	    		pictureFile = new File(path + File.separatorChar + "s_" +  imageId + "." + format);
	    		pictureFile.delete();
			}
			DbUtils.deleteAlbum(hbSession, albumId);
			hbSession.getTransaction().commit();
			response.sendRedirect("MyAlbum.jsp?root=true");
		} catch (Exception e) {
			if (hbSession != null) {
				hbSession.getTransaction().rollback();
				hbSession.close();
			}
			response.sendRedirect("Error.jsp?msg=album");
			e.printStackTrace();
		}
	}   	  	    
}